package com.kumi.shop.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.kumi.common.constant.ProductConstant;
import com.kumi.shop.product.bean.*;
import com.kumi.shop.product.mapper.AttrAttrgroupRelationMapper;
import com.kumi.shop.product.mapper.AttrGroupMapper;
import com.kumi.shop.product.mapper.CategoryMapper;
import com.kumi.shop.product.service.CategoryService;
import com.kumi.shop.product.vo.AttrGroupRespVo;
import com.kumi.shop.product.vo.AttrRespVo;
import com.kumi.shop.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kumi.common.utils.PageUtils;
import com.kumi.common.utils.Query;

import com.kumi.shop.product.mapper.AttrMapper;
import com.kumi.shop.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrMapper, Attr> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationMapper attrAttrgroupRelationMapper;

    @Autowired
    private AttrGroupMapper attrGroupMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<Attr> page = this.page(
                new Query<Attr>().getPage(params),
                new QueryWrapper<Attr>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        Attr attrEn = new Attr();
        BeanUtils.copyProperties(attr, attrEn);
        this.save(attrEn);
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_tYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelation attrAttrgroupRelation = new AttrAttrgroupRelation();
            attrAttrgroupRelation.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelation.setAttrId(attrEn.getAttrId());
            attrAttrgroupRelationMapper.insert(attrAttrgroupRelation);
        }

    }

    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<Attr> wrapper = new QueryWrapper<Attr>().eq("attr_type", "base".equalsIgnoreCase(type) ? 1:0);

        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((wrappers) -> {
                wrappers.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<Attr> page = this.page(
                new Query<Attr>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<Attr> records = page.getRecords();
        List<AttrRespVo> list = records.stream().map((attr) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attr, attrRespVo);
            if ("base".equalsIgnoreCase(type)) {
                AttrAttrgroupRelation attrId = attrAttrgroupRelationMapper.selectOne(new QueryWrapper<AttrAttrgroupRelation>().eq("attr_id", attr.getAttrId()));
                if (attrId != null && attrId.getAttrGroupId() !=null) {
                    AttrGroup attrGroup = attrGroupMapper.selectById(attrId.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroup.getAttrGroupName());
                }
            }

            Category category = categoryMapper.selectById(attr.getCatelogId());
            if (category != null) {
                attrRespVo.setCatelogName(category.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(list);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
//        AttrRespVo respVo = new AttrRespVo();
//        Attr attr = this.getById(attrId);
//        BeanUtils.copyProperties(attr,respVo);
//
//        AttrAttrgroupRelation relation = attrAttrgroupRelationMapper.selectOne(new QueryWrapper<AttrAttrgroupRelation>().eq("attr_id", attrId));
//
//        if (relation != null) {
//            respVo.setAttrGroupId(relation.getAttrGroupId());
//            AttrGroup attrGroup = attrGroupMapper.selectById(relation.getAttrGroupId());
//            if (relation != null) {
//                respVo.setGroupName(attrGroup.getAttrGroupName());
//            }
//        }
//        Long catelogId = attr.getCatelogId();
//        Long[] cateLogPath = categoryService.findCateLogPath(catelogId);
//        respVo.setCatelogPate(cateLogPath);
//        Category category = categoryMapper.selectById(catelogId);
//        if (category != null) {
//            respVo.setCatelogName(category.getName());
//        }
//        return respVo;

        AttrRespVo respVo = new AttrRespVo();
        Attr attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, respVo);

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_tYPE_BASE.getCode()) {
            AttrAttrgroupRelation relation = attrAttrgroupRelationMapper.selectOne(new QueryWrapper<AttrAttrgroupRelation>().eq("attr_id", attrId));
            if (relation != null) {
                //1、设置分组信息
                if (relation != null) {
                    respVo.setAttrGroupId(relation.getAttrGroupId());
                    AttrGroup attrGroupEntity = attrGroupMapper.selectById(relation.getAttrGroupId());
                    if (attrGroupEntity != null) {
                        respVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
        }


        //2、设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCateLogPath(catelogId);
        respVo.setCatelogPath(catelogPath);

        Category categoryEntity = categoryMapper.selectById(catelogId);
        if (categoryEntity != null) {
            respVo.setCatelogName(categoryEntity.getName());
        }


        return respVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        Attr attrEn = new Attr();
        BeanUtils.copyProperties(attr, attrEn);
        this.updateById(attrEn);

        if (attrEn.getAttrType() == ProductConstant.AttrEnum.ATTR_tYPE_BASE.getCode()) {
            AttrAttrgroupRelation relation = new AttrAttrgroupRelation();
            relation.setAttrGroupId(attr.getAttrGroupId());
            relation.setAttrId(attr.getAttrId());

            Integer id = attrAttrgroupRelationMapper.selectCount(new QueryWrapper<AttrAttrgroupRelation>().eq("attr_id", attr.getAttrId()));

            if (id > 0) {

                attrAttrgroupRelationMapper.update(relation, new UpdateWrapper<AttrAttrgroupRelation>().eq("attr_id", attr.getAttrId()));
            } else {
                attrAttrgroupRelationMapper.insert(relation);
            }
        }
    }

    @Override
    public List<Attr> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelation> relations = attrAttrgroupRelationMapper.selectList(new QueryWrapper<AttrAttrgroupRelation>().eq("attr_group_id", attrgroupId));

        List<Long> lists = relations.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        if (lists == null || lists.size() == 0){
            return null;
        }
        Collection<Attr> attrs = this.listByIds(lists);
        return (List<Attr>) attrs;
    }

    @Override
    public void deleteRelation(AttrGroupRespVo[] vos) {
        //attrAttrgroupRelationMapper.delete(new QueryWrapper<>().eq())
        List<AttrAttrgroupRelation> collect = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelation attrAttrgroupRelation = new AttrAttrgroupRelation();
            BeanUtils.copyProperties(item, attrAttrgroupRelation);
            return attrAttrgroupRelation;
        }).collect(Collectors.toList());
        attrAttrgroupRelationMapper.deleteBatchRelation(collect);
    }

    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        AttrGroup attrGroup = attrGroupMapper.selectById(attrgroupId);
        Long catelogId = attrGroup.getCatelogId();
        List<AttrGroup> groups = attrGroupMapper.selectList(new QueryWrapper<AttrGroup>().eq("catelog_id", catelogId)       );
        List<Long> collect = groups.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        List<AttrAttrgroupRelation> groupId = attrAttrgroupRelationMapper.selectList(new QueryWrapper<AttrAttrgroupRelation>().in("attr_group_id", collect));

        List<Long> collect1 = groupId.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        QueryWrapper<Attr> wrapper = new QueryWrapper<Attr>().eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_tYPE_BASE.getCode());
        if (collect1 != null && collect1.size() > 0){
            wrapper.notIn("attr_id", collect1);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((w) ->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<Attr> page = this.page(new Query<Attr>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils ;
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        return baseMapper.selectSearchAttrIds(attrIds);
    }


}